from dash import Input, Output, State
from models import db, RepairRecord,Product
from datetime import datetime
import dash

from server import server

from dash import Input, Output, State

from modules.repair.callbacks import object_as_dict,create_details_layout,reload_table_data





from pprint import pprint # 引入 pprint 方便打印
from sqlalchemy.orm.attributes import InstrumentedAttribute # 用于序列化

def register_callbacks(dash_app):

    @dash_app.callback(
        Output('repair-action-feedback', 'children', allow_duplicate=True),
        Output('repair-records-table', 'data', allow_duplicate=True),
        Output('repair-records-table', 'page_count', allow_duplicate=True),
        Output('repair-details', 'children', allow_duplicate=True), # 刷新详情
        Output('repair-selected-record-id', 'data', allow_duplicate=True), # 更新 Store
        Input('repair-order-cancel', 'n_clicks'),
        State('repair-details-record-id-store', 'data'),
        # 获取刷新表格所需的状态 (同上)
        State('repair-records-table', "page_current"),
        State('repair-records-table', "page_size"),
        State('repair-records-table', "sort_by"),
        State('repair-org-filter', 'value'),
        State('repair-dept-filter', 'value'),
        State('repair-status-filter', 'value'),
        State('repair-date-filter', 'start_date'),
        State('repair-date-filter', 'end_date'),
        State('repair-keyword-filter', 'value'),
        prevent_initial_call=True
    )
    def handle_cancel_action(n_clicks, record_id, page_current, page_size, sort_by,
                             org_shortname, dept_name, status_filter, start_date, end_date, keyword):
        if not n_clicks or not record_id:
            return dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update

        print(f"--- handle_cancel_action triggered for record ID: {record_id} ---")
        feedback_message = ""
        new_status = '已取消'

        try:
            with server.app_context():
                record = db.session.query(RepairRecord).get(record_id)
                # 假设 '待响应' 和 '维修中' 状态可以取消
                if record and record.repair_status in ['待响应', '维修中', '未完成']:
                    record.repair_status = new_status
                    record.update_time = datetime.now()
                    product = db.session.query(Product).filter_by(id=record.product_id).first()
                    if product:
                        product.running_status = 0
                    db.session.commit()
                    feedback_message = f"记录 {record_id} 已取消，状态更新为 {new_status}"
                    # print(feedback_message)
                    updated_record_dict = object_as_dict(db.session.query(RepairRecord).get(record_id))
                    new_details_layout = create_details_layout(updated_record_dict)
                elif record:
                     feedback_message = f"记录 {record_id} 当前状态为 {record.repair_status}，无法取消。"
                    #  print(feedback_message)
                     return feedback_message, dash.no_update, dash.no_update, dash.no_update, dash.no_update
                else:
                    feedback_message = f"错误：未找到记录 {record_id}"
                    # print(feedback_message)
                    return feedback_message, dash.no_update, dash.no_update, dash.no_update, dash.no_update

        except Exception as e:
            db.session.rollback()
            feedback_message = f"错误：更新记录 {record_id} 失败 - {e}"
            print(f"!!! ERROR in handle_cancel_action: {e}")
            return feedback_message, dash.no_update, dash.no_update, dash.no_update, dash.no_update

        refreshed_data, page_count = reload_table_data(
            page_current, page_size, sort_by, org_shortname, dept_name,
            status_filter, start_date, end_date, keyword
        )
        from flask import session
        from models import User
        user_id = session.get("user_id")
        if user_id:
            user = User.query.get(user_id)
            username = user.username if user else "匿名用户"
        else:
            username = "匿名用户"
        from modules.generatelogs.generatelogs import write_repair_log    
        product_id = record.product_id
        product = db.session.query(Product).filter_by(id=product_id).first()
        if product:
            device_id = product.id
        else:
            device_id = product_id  # 或者直接用 record.product_id
        write_repair_log(
            action="取消维修",
            username=username,
            device_id=device_id,
            record_id=record_id,
            message=f"取消人：{username}，描述: {updated_record_dict}"
            )
        return feedback_message, refreshed_data, page_count, new_details_layout, {'action': 'cancel', 'record_id': record_id}
